package com.smasher.widget.view;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.smasher.widget.R;


public class AvatarView extends View {

    public static final String TAG = "AvatarView";

    private Paint mPaint;
    private Bitmap mBitmap;
    private Matrix mMatrix;
    private BitmapShader mBitmapShader;

    private int drawableRes = R.drawable.user_default;
    private float defaultSizeDp = 24; // 默认大小为24dp

    public AvatarView(Context context) {
        this(context, null);
    }

    public AvatarView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AvatarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        try (TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AvatarView)) {
            drawableRes = typedArray.getResourceId(R.styleable.AvatarView_image_res, R.drawable.user_default);
        } catch (Exception e) {
            Log.e(TAG, "AvatarView: ", e);
        }
        init();
    }

    private void init() {

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // 开启抗锯齿
        mMatrix = new Matrix();
        mBitmap = BitmapFactory.decodeResource(getResources(), drawableRes);
        if (mBitmap == null) {
            mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.user_default);
        }
        mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
    }

    public void setBitmapDrawable(int drawableRes) {
        this.drawableRes = drawableRes;
        mBitmap = BitmapFactory.decodeResource(getResources(), drawableRes);
        invalidate();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 获取默认尺寸（24dp转换为px）
        final int defaultSizePx = (int) dpToPx(defaultSizeDp);

        // 确定最终的尺寸
        int size = resolveDefaultSize(widthMeasureSpec, defaultSizePx);
        size = resolveDefaultSize(heightMeasureSpec, size);

        setMeasuredDimension(size, size); // 确保宽高相同
    }

    private int resolveDefaultSize(int measureSpec, int defaultSize) {
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        switch (mode) {
            case MeasureSpec.EXACTLY:
                return size;
            case MeasureSpec.AT_MOST:
                return Math.min(size, defaultSize);
            case MeasureSpec.UNSPECIFIED:
            default:
                return defaultSize;
        }
    }

    private float dpToPx(float dp) {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        return dp * (metrics.densityDpi / 160f);
    }


    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);

        if (mBitmap == null) {
            return;
        }

        float scale = (float) getWidth() / mBitmap.getWidth();
        mMatrix.setScale(scale, scale);
        mBitmapShader.setLocalMatrix(mMatrix);
        mPaint.setShader(mBitmapShader);

        float half = getWidth() / 2f;
        canvas.drawCircle(half, half, getWidth() / 2f, mPaint);
    }
}
